package com.laycoding.layrpc.config.server;

import com.laycoding.layrpc.annotation.EnableRpcServer;
import com.laycoding.layrpc.annotation.LayRpcScan;
import com.laycoding.layrpc.annotation.LayRpcService;
import com.laycoding.layrpc.common.LayRpcServiceCache;
import com.laycoding.layrpc.config.client.LayRpcBeanName;
import com.laycoding.layrpc.config.client.LayRpcServiceClassPathScanHandle;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class LayRpcServerScan implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
    ResourceLoader resourceLoader;
    List<String> classList = new ArrayList<>();
    BeanDefinitionRegistry registry;
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
         this.resourceLoader = resourceLoader;
    }
/*
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(EnableRpcServer.class.getName()));

        String[] basePackages = annoAttrs.getStringArray("basePackage");
        //没有设置 扫描路径,就扫描对应
        if(basePackages.length == 0){
            basePackages = new String[]{((StandardAnnotationMetadata) annotationMetadata).getIntrospectedClass().getPackage().getName()};
        }

        //自定义的 包扫描器
        LayRpcServerClassPathScanHandle scanHandle = new LayRpcServerClassPathScanHandle(beanDefinitionRegistry,false);

        if(resourceLoader != null){
            scanHandle.setResourceLoader(resourceLoader);
        }

        scanHandle.setBeanNameGenerator(new LayRpcServiceBeanName());
        //扫描指定路径下的接口
        Set<BeanDefinitionHolder> beanDefinitionHolders = scanHandle.doScan(basePackages);
    }*/
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        //创建一个BeanDefinition对象
      /*  RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Book.class);
        //注册一个名为xixi的BeanDefinition
        registry.registerBeanDefinition("xixi", rootBeanDefinition);*/

        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableRpcServer.class.getName()));

        String[] basePackages = annoAttrs.getStringArray("basePackage");
        this.registry = registry;
        scanPackage(basePackages[0]);


    }


    private void registryService() {
        if (classList.size() == 0) {
            return;
        }
        for (String className : classList) {
            try {
                Class<?> clazz = Class.forName(className);
                // 服务名称
                LayRpcService declaredAnnotation = clazz.getDeclaredAnnotation(LayRpcService.class);
                if (!StringUtils.isEmpty(declaredAnnotation) && clazz.getInterfaces().length > 0) {
                    Class<?> anInterface = clazz.getInterfaces()[0];
                    RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(clazz);
                    String simpleName = anInterface.getName();
                    registry.registerBeanDefinition(simpleName,rootBeanDefinition);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void scanPackage(String packageName) {
        ClassLoader classLoader = this.getClass().getClassLoader();
        URL url = classLoader.getResource(packageName.replaceAll("\\.", "/"));
        File dir = new File(url.getFile());
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                scanPackage(packageName + "." + file.getName());
            } else {
                // 拿出类名
                String className = packageName + "." + file.getName().replace(".class", "").trim();
                classList.add(className);
            }
        }
        registryService();
    }
}
